package br.com.cfccultura.admin.model.dao.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import br.com.cfccultura.admin.model.dao.IServicoDAO;
import br.com.cfccultura.admin.model.enums.Ativo;
import br.com.cfccultura.admin.model.vo.Servico;

@Repository
public class ServicoDAO extends DAO implements IServicoDAO {

	@Override
	public List<Servico> consultar(Servico vo) {

		String sql = "SELECT cd_servico, dc_servico, vl_venda, vl_custo, id_ativo FROM tb_servico where ";
		Object[] params;
		if(vo.getCodigo() != null) {
			sql += "cd_servico = ? ";
			params = new Object[]{vo.getCodigo()};
		} else {
			sql += "dc_servico like ? ";
			String desc = "%";
			if(vo.getDescricao() != null && !vo.getDescricao().equals("")) {
				desc = vo.getDescricao() + "%";
			}
			params = new Object[]{desc};
		}
		sql += "and id_ativo = 1 order by dc_servico";

		List<Servico> result = query(sql, params, new RowMapper<Servico>() {
			@Override
			public Servico mapRow(ResultSet rs, int arg1) throws SQLException {
				Servico vo = new Servico();
				vo.setCodigo(rs.getInt("cd_servico"));
				vo.setDescricao(rs.getString("dc_servico"));
				vo.setValorVenda(rs.getDouble("vl_venda"));
				vo.setValorCusto(rs.getDouble("vl_custo"));
				vo.setAtivo(Ativo.setValue(rs.getInt("id_ativo")));
				return vo;
			}
			
		});		
		
		return result;
	}
	
	@Override
	public Servico consultar(Integer id) {
		List<Servico> servicos = consultar(new Servico(id));
		return servicos.get(0);
	}
	
	@Override
	public void incluir(Servico vo) {
		String sql = "INSERT INTO tb_servico(dc_servico, vl_venda, vl_custo) values(?,?,?)";
		update(sql, new Object[] {vo.getDescricao(), vo.getValorVenda(), vo.getValorCusto()});
	}
	
	@Override
	public void alterar(Servico vo) {
		String sql = "UPDATE tb_servico set dc_servico = ?, vl_venda = ?, vl_custo = ? where cd_servico = ?";
		update(sql, new Object[] {vo.getDescricao(), vo.getValorVenda(), vo.getValorCusto(), vo.getCodigo()});
	}
	
	@Override
	public void excluir(Integer id) {
		try {
			String sql = "DELETE FROM tb_servico where cd_servico = ?";
			update(sql, new Object[] {id});
		} catch(DataIntegrityViolationException e) {
			String sql = "UPDATE tb_servico set id_ativo = 0 where cd_servico = ?";
			update(sql, new Object[] {id});
		}
	}

}
